package cn.zqy.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.zqy.model.BookStatus;
import cn.zqy.model.Library;
import cn.zqy.model.LibraryActions;
import cn.zqy.services.LibraryService;
import cn.zqy.services.MailService;
import cn.zqy.services.Utils;

public class LibraryServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;	

	private final Logger log = Logger.getLogger(this.getClass().getName());

	public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException
	{
		String flag = req.getParameter("flag");
		if (flag == null || flag.length() == 0)
		{//do nothing
			res.sendRedirect("/library.jsp");
		}
		else if (LibraryActions.ADD.toString().equalsIgnoreCase(flag))
		{
			addBook(req, res);
		}
		else if (LibraryActions.UPDATE.toString().equalsIgnoreCase(flag))
		{
			updateBook(req, res);
		}
		else if (LibraryActions.LEND.toString().equalsIgnoreCase(flag))
		{
			lendBook(req, res);
		}
		else if (LibraryActions.RETURN.toString().equalsIgnoreCase(flag))
		{
			returnBook(req, res);
		}
		else if (LibraryActions.RESERVE.toString().equalsIgnoreCase(flag))
		{
			reserveBook(req, res);
		}
		else if (LibraryActions.DELETE.toString().equalsIgnoreCase(flag))
		{
			deleteBook(req, res);
		}
		
	}

	private void deleteBook(HttpServletRequest req, HttpServletResponse res) throws IOException
	{
		if (Utils.isAuthorized())
		{
			String bookNo = req.getParameter("book_no");
			/*HashMap<String, String> paramsMap = new HashMap<String, String>();
			paramsMap.put("bookNo", bookNo);
			ArrayList<Library> libraryList = new LibraryService().retrieveAll(paramsMap);
			if (libraryList.size() > 0)
			{
				Library library = libraryList.get(0);
				
				new LibraryService().delete(library);
			}*/
			new LibraryService().delete(bookNo);
		}
		res.sendRedirect("/library.jsp");
	}

	private void updateBook(HttpServletRequest req, HttpServletResponse res) throws IOException
	{
		if (Utils.isAuthorized())
		{
			String bookNo = req.getParameter("book_no");
			String bookName = req.getParameter("book_name");
			String bookLanguage = req.getParameter("book_language");
			String bookStatus = req.getParameter("book_status");
			String borrower = req.getParameter("borrower");
			String bookOwner = req.getParameter("book_owner");
			HashMap<String, String> paramsMap = new HashMap<String, String>();
			paramsMap.put("bookNo", bookNo);
			ArrayList<Library> libraryList = new LibraryService().retrieveAll(paramsMap);
			if (libraryList.size() > 0)
			{
				Library library = libraryList.get(0);
				library.setBookName(bookName);
				library.setLanguage(bookLanguage);
				library.setBookStatus(bookStatus);
				library.setBorrower(borrower);
				library.setBookOwner(bookOwner);
				new LibraryService().update(library);
			}
		}
		res.sendRedirect("/library_admin.jsp");
	}

	private void lendBook(HttpServletRequest req, HttpServletResponse res) throws IOException
	{
		if (Utils.isAuthorized())
		{
			String bookNo = req.getParameter("book_no");
			String borrower = req.getParameter("borrower");
			HashMap<String, String> paramsMap = new HashMap<String, String>();
			paramsMap.put("bookNo", bookNo);
			ArrayList<Library> libraryList = new LibraryService().retrieveAll(paramsMap);
			if (libraryList.size() > 0)
			{
				Library library = libraryList.get(0);
				library.setBorrower(borrower);
				library.setContact("");
				library.setBookStatus(BookStatus.OUT.getValue());
				library.setDateToLend(new Date());
				new LibraryService().update(library);
			}
		}
		res.sendRedirect("/library_admin.jsp");
		
	}

	private void addBook(HttpServletRequest req, HttpServletResponse res) throws IOException
	{
		if (Utils.isAuthorized())
		{
			String bookNo = req.getParameter("book_no");
			String bookName = req.getParameter("book_name");
			String bookLanguage = req.getParameter("book_language");
			String bookStatus = req.getParameter("book_status");
			String bookOwner = req.getParameter("book_owner");
			if (bookNo != null && bookNo.length() > 0)
			{
				Library library = new Library();
				library.setBookNo(bookNo);
				library.setBookName(bookName);
				library.setLanguage(bookLanguage);
				library.setBookStatus(bookStatus);
				library.setBookOwner(bookOwner);
				new LibraryService().persistent(library);
			}
		}
		res.sendRedirect("/library_admin.jsp");
	}

	public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException
	{		
/*		String flag=req.getParameter("flag");
		if(LibraryActions.RETURN.toString().equalsIgnoreCase(flag))
		{
			returnBook(req,res);
		} else if(LibraryActions.RESERVE.toString().equalsIgnoreCase(flag))
		{
			reserveBook(req,res);
		}*/
		doPost(req,res);
	}

	private void reserveBook(HttpServletRequest req, HttpServletResponse res) throws IOException
	{
		String bookNo = req.getParameter("book_no");
		String contact =req.getParameter("contact");
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("bookNo", bookNo);
		ArrayList<Library> libraryList = new LibraryService().retrieveAll(paramsMap);
		if (libraryList.size() > 0)
		{
			Library library=libraryList.get(0);
			library.setContact(contact);			
			new LibraryService().update(library);
		}
		res.sendRedirect("/library.jsp");
	}

	private void returnBook(HttpServletRequest req, HttpServletResponse res) throws IOException
	{
		if (Utils.isAuthorized())
		{
			String bookNo = req.getParameter("book_no");
			HashMap<String, String> paramsMap = new HashMap<String, String>();
			paramsMap.put("bookNo", bookNo);
			ArrayList<Library> libraryList = new LibraryService().retrieveAll(paramsMap);
			if (libraryList.size() > 0)
			{
				Library library=libraryList.get(0);
				library.setBookStatus(BookStatus.IN.getValue());
				library.setBorrower("");				
				new LibraryService().update(library);
				if(library.getContact()!=null&&Utils.isValidEmail(library.getContact()))
				{
					MailService mailService=new MailService();
					mailService.setFromAddress("mphasis2010@gmail.com");
					mailService.setSubject(library.getBookName()+" Return!");
					mailService.setToAddress(library.getContact());
					mailService.setBody("The Book you reqeust for "+library.getBookName()+" is return!");
					try
					{
						mailService.sendMail();
					}
					catch (Exception e)
					{
						log.log(Level.SEVERE, e.toString());
					}
				}
			}
		}
		res.sendRedirect("/library_admin.jsp");
	}
/*
	private void query(HttpServletRequest req, HttpServletResponse res) throws IOException
	{
		String bookStatus=req.getParameter("book_status");
		String language=req.getParameter("book_language");
		String bookNo=req.getParameter("book_no");
		String bookName=req.getParameter("book_name");
		HashMap<String,String> paramsMap=new HashMap<String,String>();
		
		if(bookStatus!=null && bookStatus.length()>0)
		{
			paramsMap.put("bookStatus", bookStatus);
		}
		if(language!=null && language.length()>0)
		{
			paramsMap.put("language", language);
		}
		if(bookNo!=null && bookNo.length()>0)
		{
			paramsMap.put("bookNo", bookNo);
		}
		if(bookName!=null && bookName.length()>0)
		{
			paramsMap.put("bookName", bookName);
		}
		ArrayList<Library> libraryList=new LibraryService().retrieveAll(paramsMap);
		StringBuffer htmlSb=new StringBuffer();
		if(libraryList.size()>0)
		{
			htmlSb.append("<table align='left'>");
			htmlSb.append("<tr><td>Name</td><td>Language</td><td>Status</td><td>Action</td></tr>");
			for(Library library:libraryList)
			{
				boolean isIn=library.getBookStatus().startsWith("I")?true:false;
				htmlSb.append("<tr>");
				if(Utils.isAuthorized())
				{
					htmlSb.append("<td><a href=\"/library_update.jsp?book_no="+library.getBookNo()+"&flag=update\">"+library.getBookName()+"</a></td>");
				}
				else
				{
					htmlSb.append("<td>"+library.getBookName()+"</td>");
				}
				htmlSb.append("<td>"+library.getLanguage()+"</td><td>"+library.getBookStatus()+"</td><td>");
				String flag="reserve";
				String action="To Reserve";
				if(Utils.isAuthorized())
				{//for administrator
					if(isIn)
					{
						flag="lend";
						action="To Lend";
						htmlSb.append("<a href=\"/library_update.jsp?book_no="+library.getBookNo()+"&flag="+flag+"\">"+action+"</a></td></tr>");
					}
					else
					{
						flag="return";
						action="To Return";
						htmlSb.append("<a href=\"/Library?book_no="+library.getBookNo()+"&flag="+flag+"\">"+action+"</a></td></tr>");
					}
					
				}
				else
				{//for others
					if(isIn)
					{
						htmlSb.append("<a href=\"/library_update.jsp?book_no="+library.getBookNo()+"&flag="+flag+"\">"+action+"</a></td></tr>");
					}
					else
					{
						htmlSb.append("&nbsp;</td></tr>");
					}
				}
			}
			htmlSb.append("</table>");
		}
		if(htmlSb.length()==0)
		{
			htmlSb.append("No data found!");
		}
		res.setContentType("text/html; charset=utf-8");
		PrintWriter out = res.getWriter();
		out.println(htmlSb.toString());
	}*/	
}
